<?php 
	require_once("../config/db.php");
	require_once('../model/Battleground.php');

	$jsonObj = $_GET['json'];
	$size = ($_GET['size'] - 1) * 42 ;
	$ship1 = $_GET['ship1'];
	$ship2 = $_GET['ship2'];
	$idShip = $_GET['idShip'];
	$x = $_GET['x'];
	$y = $_GET['y'];
	$dir = $_GET['sens'][0];
	$sens = $_GET['sens'][1] ;

	if($_GET['player'] == 1){
		$ship1[$idShip][3]['x'] = $x;
		$ship1[$idShip][3]['y'] = $y;
	}
	else {
		$ship2[$idShip][3]['x'] = $x;
		$ship2[$idShip][3]['y'] = $y;
	}
	$ng = new Game(0);
	$ng->reconstruct($jsonObj['idP1'], $jsonObj['idP2'], $ship1, $ship2);

	$bg = new Battleground($jsonObj['idGame'], $jsonObj['idP1'], $jsonObj['idP2'], 0);
	$id = $bg->__get('idP'.$_GET['player']);

	$xPos = $xNeg = $x;
	$yPos = $yNeg = $y;
	$arraxy = array();
	$arraxy[0]['x'] = $x;
	$arraxy[0]['y'] = intval($y);
	if($dir == 'x'){
		if($sens == '+'){
			$transform = array(0 => 'rotate', 1 => '-90');
			for($i=1; $i <= $_GET['size'] - 1; $i++) {
				$shiftPos = array_keys($bg->battlefield, $xPos);
				$indexXpos = $shiftPos[0];
				$xPos = $bg->battlefield[$indexXpos+1];
				$arraxy[$i]['x'] = $xPos;
				$arraxy[$i]['y'] = intval($y);
			}
		}
		elseif($sens == '-'){
			$transform = array(0 => 'rotate', 1 => '90');
			for($i=1; $i <= $_GET['size'] - 1; $i++) {
				$shiftNeg = array_keys($bg->battlefield, $xNeg);
				$indexXneg = $shiftNeg[0];
				$xNeg = $bg->battlefield[$indexXneg-1];
				$arraxy[$i]['x'] = $xNeg;
				$arraxy[$i]['y'] = intval($y);
			}
		}
	}
	elseif($dir == 'y'){
		if($sens == '+'){
			$transform = array(0 => '', 1 => '');
			for($i=1; $i <= $_GET['size'] - 1; $i++) {
				$yPos++;
				$arraxy[$i]['x'] = $x;
				$arraxy[$i]['y'] = intval($yPos);
			}
		}
		elseif($sens == '-'){
			$transform = array(0 => 'translate', 1 => $size);
			for($i=1; $i <= $_GET['size'] - 1; $i++) {
				$yNeg--;
				$arraxy[$i]['x'] = $x;
				$arraxy[$i]['y'] = intval($yNeg);
			}
		}
	}
	$bg->setStartPosition($id, $jsonObj['idGame'], $arraxy);
	$posShip['player'] = $id ;
	if($_GET['player'] == 1){
		$posShip['ship'] = $ship1[$idShip] ;
	}
	else {
		$posShip['ship'] = $ship2[$idShip] ;
	}
	$posShip['shipP1'] = $ng->player_1->ships;
	$posShip['shipP2'] = $ng->player_2->ships;
	$posShip['transform'] = $transform;
	$posShip['x'] = $x;
	$posShip['y'] = $y;

	header("Content-type: application/json");
	echo json_encode($posShip);

?>